#!/bin/sh
#
# memory-usage analyzer
# Copyright (C) 2023 Distopico <distopico@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Description:
# --------------
#
# Check memory usage by process/program in an interval of time
# and save the result data into a file, you can use the data with
# gnuplot or other tools.
#
# Requirements:
# --------------
# - grep or pgrep
# - procps (for `ps` command)
#
# Usage:
#
# ./memory-usage $(node | grep script.js)
# Output: $ top.data with lines such as `1539689171 305m 2.0`, i.e. unix time - memory with % suffix - CPU load in %
#
# Type `-h` to more examples and available parameters

function show_usage() {
    local script_name="$(basename $0)"

    echo "Usage: $script_name [-n name_file (default top.data)] [-d max_duration (default 180sec)] [-a max_attempts (default 1000)] <process_name>"
    echo
    echo 'Arguments:'
    echo -e '\t-n name_file\t name of the file to save cpu stats data'
    echo -e '\t-d max_duration\t duration time in seconds to watch the process'
    echo -e '\t-a max_attempts\t how many attempts to check if the process is running before exit'
    echo -e '\t-o overwrite\t overwrite output file'
    echo -e '\t-h show this menu'
    echo
    echo 'Example:'
    echo -e '\t./memory-usage -d 90 -a 100 -n top2.data $(node | grep script.js)'
}

function _pgrep() {
    if ! [[ -x "$(command -v pgrep)" ]]; then
        # Set pgrep fallback
        ps axf | grep "$1" | grep -v grep | awk '{print $1}'
    else
        pgrep $@
    fi
}

OPTIND=1
while getopts ':a:d:n:o:h' opt; do
    case "$opt" in
        a  ) _max_attempts="$OPTARG" ;;
        d  ) _max_duration="$OPTARG" ;;
        n  ) _name_output="$OPTARG"  ;;
        o  ) _overwrite="$OPTARG"    ;;
        h  ) show_usage; exit 0      ;;
        \? ) echo "Unknown option: -$OPTARG" >&2; exit 1 ;;
        :  ) echo "Missing argument for option: -$OPTARG" >&2; exit 2 ;;
    esac
done

shift $((OPTIND - 1))

[ "$1" = '--' ] && shift

process_name=$1
output="${_name_output-top.data}"
max_attempts=${_max_duration-1000}
max_time=${_max_attempts-180}
should_overwrite="${_overwrite-false}"
attempts=0

[ -z "$process_name" ] && echo -e "Proccess is require\n" && show_usage && exit 1

while [ $attempts -le $max_attempts ]
do
    echo "_pgrep -lfa $process_name"
    pid_process=$(_pgrep -lfa $process_name | awk '{print $1}')
    if [ ! -z "$pid_process" ]
    then
        echo "Found PID $pid_process"
        break
    fi
    echo "Watting to process"
    attempts=$(( $attempts + 1 ))
done

if [ -z "$pid_process" ]
then
    echo "Not PID found"
    unset _PROCESS_PID
    exit 0
fi

if [ -f "$output" ] && [ "$should_overwrite" != "true" ]; then
    echo $should_overwrite
    echo "Already exist file with name: $output, use [-o true] to overwrite"
    exit 0
fi

echo "Checking memory/cpu usage"

seconds=0
time=$((seconds+max_time))
export _PROCESS_PID=$pid_process

while [ $seconds -lt $time ]; do ps -o pmem,pcpu $_PROCESS_PID | grep -E '^\s[0-9]+' | awk -v now=$(date +%s) '{print now,$1,$2}' >> $output; done

unset _PROCESS_PID
echo "done"
